<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/8/12
 * Time: 11:40
 */
namespace App\Repositories;

use App\Models\Message;

class MessageRepository
{
    /**
     * 创建消息
     * @param array $params
     * @return mixed
     */
    public function create(array $params)
    {
        return Message::create($params);
    }

    /**
     * 查找一条记录
     * @param $id
     * @return mixed
     */
    public function byId($id)
    {
        return Message::find($id);
    }

    public function getProfitAll($limit = 100)
    {
        return Message::where('msg_type', '0001')
            ->whereIn('scene', [7,8,9,10,11])
            ->orderBy('id', 'desc')
            ->limit($limit)
            ->get();
    }

    public function getCount($toUserId, $msgType)
    {
        return Message::where([
            'to_user_id' => $toUserId,
            'msg_type' => $msgType,
            'is_read' => 0
        ])->count();
    }

    /**
     * 根据业务场景获取所有记录
     * @param $toUserId
     * @param $msgType
     * @param $page
     * @param $limit
     * @return mixed
     */
    public function getAllToScene($toUserId, $msgType, $page, $limit)
    {
        $page -= 1;
        $page = $page < 0 ? 0 : $page;
        $offset = $page * $limit;
        $result = Message::where([
            'to_user_id' => $toUserId,
            'msg_type' => $msgType,
        ])
            ->offset($offset)
            ->limit($limit)
            ->orderBy('is_read', 'asc')
            ->orderBy('id', 'desc')
            ->get();
        $data = [];
        if (!empty($result)) {
            foreach ($result as $key=>$value) {
                $data[$key] = $value;
                $data[$key]['image_url'] = !empty($value['image_url']) ? getOssImageUrl($value['image_url']) : '';
            }
        }
        return $data;
    }

    /**
     * 更新个人已读
     * @param $id
     * @return mixed
     */
    public function updateRead($id, $toUserId)
    {
        return Message::where([
            'id' => $id,
            'to_user_id' => $toUserId,
            'msg_type' => '0001',
            'is_read' => 0,
        ])->update([
            'is_read' => 1,
            'update_time' => time()
        ]);
    }

    /**
     * 更新全部已读
     * @return mixed
     */
    public function updateReadAll($toUserId)
    {
        return Message::where([
            'to_user_id' => $toUserId,
            'msg_type' => '0001',
            'is_read' => 0,
        ])->update([
            'is_read' => 1,
            'update_time' => time()
        ]);
    }

}